import java.util.*;

/**
 * Created by liukaixin on 16/5/19.
 */
public class TicketMaker {

    private Map<String, Integer> barcodeAndCountMap = new HashMap<>();

    public void setGoods(String jsonString) {
        String[] goods = JSONDecoder.decodeArrayFrom(jsonString);
        for (String tmp : Arrays.asList(goods)) {
            String[] barcode = tmp.split("-");
            if (barcode.length == 2) {
                Integer count = barcodeAndCountMap.get(barcode[0]);
                barcodeAndCountMap.put(barcode[0], (count == null) ? Integer.parseInt(barcode[1]) : count + Integer.parseInt(barcode[1]));
            } else {
                Integer count = barcodeAndCountMap.get(barcode[0]);
                barcodeAndCountMap.put(barcode[0], (count == null) ? 1 : count + 1);
            }
        }
    }

    public void printTicket() {
        System.out.println("***<没钱赚商店>购物清单***");
        Product product;
        for (Map.Entry entry : barcodeAndCountMap.entrySet()) {
            product = ProductManager.getProductManager().getProductByBarcode(entry.getKey().toString());
            System.out.printf("名称:%s, 数量:%d%s,单价:%.2f(元),小计:%.2f(元)\n", product.getName(), entry.getValue(), product.getUnit(), product.getPrice(), getTotalPriceFor(product.getBarcode()));
        }

        System.out.println("----------------------");

        if (DiscountManager.getDiscountManager().getGoodsBeingDiscountedsList().size() > 0) {
            System.out.println("买三免一商品:");
            GoodsBeingDiscounted goodsBeingDiscounted;
            double reducePrice = 0.00;
            for (int i = 0; i < DiscountManager.getDiscountManager().getGoodsBeingDiscountedsList().size(); i++) {
                goodsBeingDiscounted = DiscountManager.getDiscountManager().getGoodsBeingDiscountedsList().get(i);
                reducePrice += goodsBeingDiscounted.getPriceBeforeDiscount() - goodsBeingDiscounted.getPriceAfterDiscount();
                System.out.printf("名称:%s,数量:%d\n", goodsBeingDiscounted.getName(), goodsBeingDiscounted.getOriginCount() - goodsBeingDiscounted.getActualCount());
            }
            System.out.println("----------------------");
            System.out.printf("总计:%.2f(元)\n节省:%.2f(元)\n", getTotalPrice(), reducePrice);
        } else {
            System.out.printf("总计:%.2f(元)\n", getTotalPrice());
        }
        System.out.println("**********************");
    }

    public int getCountOf(String barcode) {
        return barcodeAndCountMap.get(barcode);
    }

    public double getTotalPriceFor(String barcode) {
        DiscountManager discountManager = DiscountManager.getDiscountManager();
        return discountManager.NewGetTotalPriceAfterDiscountFor(barcode, getCountOf(barcode));
    }

    public double getTotalPrice() {
        double sum = 0.00;
        for (Map.Entry entry : barcodeAndCountMap.entrySet()) {
            sum += getTotalPriceFor(entry.getKey().toString());
        }
        return sum;
    }
}
